//
//  NSString+Extension.m
//  JWBrowser
//
//  Created by byAlex on 14-11-7.
//  Copyright (c) 2014年 JW. All rights reserved.
//

#import "NSString+Extension.h"
#import <CommonCrypto/CommonDigest.h>

#if __has_feature(objc_arc)
#define SAFE_AUTORELEASE(a) (a)
#else
#define SAFE_AUTORELEASE(a) [(a) autorelease]
#endif

@implementation NSString (Extension)

- (BOOL)containsString:(NSString *)aString
{
    if (aString == nil) {
        return NO;
    }
    NSRange rang = [self rangeOfString:aString];
    if (rang.length) {
        return YES ;
    }
    
    return NO;
}

- (BOOL)containsStringArray:(NSArray *)stringArray
{
    __block BOOL isOK = NO;
    [stringArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *string = obj;
        BOOL b = [self containsString:string];
        if (b) {
            isOK = YES;
        }
    }];
    return isOK;
}

- (BOOL)isContainChinese
{
    BOOL isContain = NO;
    for (int i = 0; i<self.length; i++)
    {
        NSRange range = NSMakeRange(i, 1);
        NSString *tpString = [self substringWithRange:range];
        const char *cString=[tpString UTF8String];
        if (strlen(cString)==3)
        {
            isContain = YES;
            break;
        }
    }
    return isContain;
}

- (BOOL)isEmpty
{
    if (self == nil || [self isEqualToString:@""]) {
        return YES;
    }else return NO;
}

- (NSString *)removeString:(NSString *)string
{
    if (!string) {
        return @"";
    }
    NSArray *array = [self componentsSeparatedByString:string];
    return [array componentsJoinedByString:@""];
}

- (NSString *)trimLeftAndRightWhiteSpace
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)trimAllWhiteSpace
{
    return [[self stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
}


- (NSString *)URLEncodeString
{
    return [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

// Use Core Foundation method to URL-encode strings, since -stringByAddingPercentEscapesUsingEncoding:
// doesn't do a complete job. For details, see:
//   http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/
//   http://stackoverflow.com/questions/730101/how-do-i-encode-in-a-url-in-an-html-attribute-value/730427#730427
- (NSString *)URLEncodeAllString
{
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                                    (__bridge CFStringRef)self,
                                                                                                    NULL,
                                                                                                    (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                                    kCFStringEncodingUTF8));
    return encodedString;
}

- (NSString *)URLDecodeString
{
    return [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSInteger)hexInteger
{
    unsigned result = 0;
    NSScanner *scanner = [NSScanner scannerWithString:self];
    
    [scanner setScanLocation:2]; // bypass '#' character
    [scanner scanHexInt:&result];
    return result;
}

- (NSString *) stringFromMD5{
    
    if(self == nil || [self length] == 0)
        return nil;
    
    const char *value = [self UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    return SAFE_AUTORELEASE(outputString);
}

-(NSString *) md5
{
    const char *cStr = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}

- (NSString*) sha1
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

- (VersionCompareResult)versionCompareWithOtherVersion:(NSString *)otherVersion
{
    NSComparisonResult rst = [self compare:otherVersion options:NSNumericSearch];
    switch (rst) {
        case NSOrderedAscending:
            return VersionCompareResultLitte;
            break;
        case NSOrderedDescending:
            return VersionCompareResultLarge;
            break;
        case NSOrderedSame:
            return VersionCompareResultEqual;
            break;
        default:
            break;
    }
    return VersionCompareResultNoRst;
}

- (BOOL)isValidURL
{
    //判断否是网址
    NSString *noHttpString = [[self removeString:@"http://"]removeString:@"https://"];
    NSArray *commponents = [noHttpString componentsSeparatedByString:@"/"];
    NSString *site = nil;
    if (commponents.count)
    {
        site = [commponents objectAtIndex:0];
    }
    
    NSRange rangeSite = [site rangeOfString:@"([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$" options:NSRegularExpressionSearch];
    NSRange rangeIp = [site rangeOfString:@"(([0-9]{1,3}\\.)+)([0-9]{1,3})" options:NSRegularExpressionSearch];
    NSString *searchString = [self URLEncodeString];
    if (rangeSite.length>0 || rangeIp.length>0 || [searchString containsStringArray:@[@"http",@"https"]])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (NSString *)convertToValidURL
{
    if (self.isValidURL) {
        if ([self hasPrefix:@"http://"] || [self hasPrefix:@"https://"]) {
            return self;
        }else
        {
            return [NSString stringWithFormat:@"http://%@",self];
        }
    }else return nil;
}

- (NSData *)dataUTF8
{
    return [self dataUsingEncoding:NSUTF8StringEncoding];
}


@end
